<template>
  <view class="order-card" @click.stop="onViewDetail">
    <view class="order-logistics">
      <view class="order-tag">快递配送</view>
      <view class="order-address">{{
        props.detail.receiverProvince +
        props.detail.receiverCity +
        props.detail.receiverRegion +
        props.detail.receiverDetailAddress
      }}</view>
      <view class="order-status">{{
        orderStatusFilter(props.detail.orderStatus)
      }}</view>
    </view>
    <view class="order-goods">
      <view
        class="flex mb-10px"
        v-for="item in props.detail.items"
        :key="item.id"
      >
        <view
          class="goods-cover cover"
          :style="{ backgroundImage: `url(${item.productImageUrl})` }"
        ></view>
        <view class="flex" style="width: 100%">
          <view class="goods-name line-clamp-2">
            {{ item.productName }}
          </view>
          <view class="order-total">
            <view class="goods-price">¥{{ item.productSkuPrice }}</view>
            <view class="goods-count">x{{ item.productSkuQuantity }}</view>
          </view>
        </view>
      </view>
      <view class="flex items-end justify-end leading-none mt-16px text-s">
        <label class="mr-5px"
          >共{{ props.detail.items.length || 0 }}件商品</label
        >实付款：
        <view class="price">
          <view class="master" style="font-weight: normal">{{
            cal.jia(props.detail.finalAmount, props.detail.freightAmount)
          }}</view>
          <!-- <label>.00</label> -->
        </view>
      </view>

      <view class="order-handle">
        <button
          v-if="props.detail.orderStatus === 2"
          @click.stop="
            linkTo('/personalPages/order/logisticsDetail?id=' + props.detail.id)
          "
        >
          查看物流
        </button>
        <button
          class="primary"
          v-if="props.detail.orderStatus === 2"
          @click.stop="ConfirmReceive(props.detail.id)"
        >
          确认收货
        </button>
        <button
          class="primary"
          v-if="
            props.detail.orderStatus === 0 || props.detail.orderStatus === 6
          "
          @click.stop="toPay(props.detail.id)"
        >
          立即付款
        </button>
        <button
          v-if="
            props.detail.orderStatus === 0 || props.detail.orderStatus === 6
          "
          @click.stop="cancel(props.detail)"
        >
          取消订单
        </button>
        <button
          class="delete"
          v-if="
            props.detail.orderStatus === 3 ||
            props.detail.orderStatus === 4 ||
            props.detail.orderStatus === 5
          "
          @click.stop="deleOrder(props.detail.id)"
        >
          删除订单
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { defineProps, defineEmits } from "vue";
import {
  wxOrderPurchase,
  cancelOrder,
  deleteOrder,
  receiveConfirm,
} from "@/services/mall";
import { orderStatusFilter } from "@/utils/utils";
import { message, debounce } from "@/utils/utils";
import { cal } from "@/utils/cal";

const props = defineProps({
  detail: {
    type: Object,
    default: () => ({}),
  },
});

const emits = defineEmits(["getList"]);

const linkTo = (url) => uni.navigateTo({ url });

// 立即支付
const toPay = async (id) => {
  getApp().emdlz(
    "track",
    "event",
    "store_page",
    "click",
    `order_pay_${id}`,
    `${props.detail.finalAmount}`
  );
  getApp()
    .sr()
    .track("custom_order", {
      order: {
        order_id: props.detail.id,
        order_time: Date.now(),
        order_status: "pay",
      },
      sub_orders: [
        {
          sub_order_id: props.detail.id,
          order_amt: props.detail.totalAmount,
          pay_amt: props.detail.finalAmount,
        },
      ],
      // more...
    });

  const res = await wxOrderPurchase({ id, appId: process.env.WXAPPID });
  if (res?.code === 200) {
    uni.requestPayment({
      provider: "wxpay", //支付类型-固定值
      timeStamp: res.data.timeStamp, // 时间戳（单位：秒）
      nonceStr: res.data.nonceStr, // 随机字符串
      package: res.data.package, // 固定值
      signType: res.data.signType, //固定值
      paySign: res.data.paySign, //签名
      success: async function (res) {
        console.log("success:" + JSON.stringify(res));

        getApp()
          .sr()
          .track("custom_order", {
            order: {
              order_id: props.detail.id,
              order_time: Date.now(),
              order_status: "payed",
            },
            sub_orders: [
              {
                sub_order_id: props.detail.id,
                order_amt: props.detail.totalAmount,
                pay_amt: props.detail.finalAmount,
              },
            ],
            // more...
          });
        await message("支付成功", 1000);
        uni.reLaunch({
          url: "/pages/paySuccess/index",
        });
      },
      fail: function (err) {
        console.log("fail:" + JSON.stringify(err));
        getApp()
          .sr()
          .track("custom_order", {
            order: {
              order_id: props.detail.id,
              order_time: Date.now(),
              order_status: "cancel_pay",
            },
            sub_orders: [
              {
                sub_order_id: props.detail.id,
                order_amt: props.detail.totalAmount,
                pay_amt: props.detail.finalAmount,
              },
            ],
            // more...
          });
        uni.showModal({
          title: "确定取消支付吗？",
          content: "120分钟内未付款，订单将自动关闭，请尽快付款哦！",
          cancelText: "稍后付款",
          confirmText: "继续付款",
          success: function (res) {
            if (res.confirm) {
              console.log("用户点击确定");
              toPay(id);
            } else if (res.cancel) {
              console.log("用户点击取消");
              message("取消支付");
            }
          },
        });
      },
    });
  } else {
    message(res.message);
  }
};

// 取消订单
const cancel = debounce(
  async (item) => {
    getApp().emdlz(
      "track",
      "event",
      "store_page",
      "click",
      `order_cancel_${item.id}`,
      `${item.finalAmount}`
    );
    const res = await cancelOrder({ id: item.id });
    if (res?.code === 200) {
      getApp()
        .sr()
        .track("custom_order", {
          order: {
            order_id: item.id,
            order_time: Date.now(),
            order_status: "cancel_give_order",
          },
          sub_orders: [
            {
              sub_order_id: item.id,
              order_amt: item.totalAmount,
              pay_amt: item.finalAmount,
            },
          ],
          // more...
        });
      await message("取消成功", 2000);
      emits("getList");
    } else {
      message(res.message);
    }
  },
  500,
  false
);

// 删除订单
const deleOrder = debounce(
  (id) => {
    uni.showModal({
      content: "确定是否删除此订单？",
      success: async function (res) {
        if (res.confirm) {
          console.log("用户点击确定");
          const res = await deleteOrder(id);
          if (res?.code === 200) {
            await message("删除成功", 2000);
            emits("getList");
          } else {
            message(res.message);
          }
        } else if (res.cancel) {
          console.log("用户点击取消");
        }
      },
    });
  },
  500,
  false
);

// 确认收货
const ConfirmReceive = debounce(
  async (id) => {
    const res = await receiveConfirm({ id: id });
    if (res?.code === 200) {
      await message("确认收货", 2000);
      emits("getList");
    } else {
      message(res.message);
    }
  },
  500,
  false
);

const onViewDetail = () => {
  uni.navigateTo({ url: "/personalPages/order/detail?id=" + props.detail.id });
};
</script>

<style lang="less" scoped>
@import "@/static/css/theme.less";

.order-card {
  margin-bottom: 10px;
  padding: 10px 9px 0px 9px;
  box-sizing: border-box;
  background: white;
  border-radius: 2px;

  .order-logistics {
    display: flex;
    align-items: center;
    font-weight: bold;
    line-height: 1;
    padding-bottom: 10px;
    border-bottom: 1px solid #f2f2f2;

    .order-address {
      flex: 1;
      font-size: 14px;
      color: @label-color;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      padding: 0 2px 0 6px;
    }

    .order-status {
      font-size: 14px;
      color: @primary-color;
    }
  }

  .order-goods {
    padding: 10px 0 0 0;

    .goods-cover {
      width: 68px;
      min-width: 68px;
      height: 68px;
      border-radius: 4px;
      background-color: rgba(0, 0, 0, 0.2);
    }

    .goods-name {
      padding: 0 12px 0 8px;
      box-sizing: border-box;
      font-size: 14px;
      flex: 1;
      height: 40px;
      font-weight: 500;
    }

    .order-total {
      color: #353535;
      text-align: right;
      font-size: 14px;

      .goods-count {
        font-size: 12px;
        color: #818181;
        line-height: 1;
        margin-top: 5px;
      }
    }

    .order-handle {
      width: 100%;
      display: flex;
      justify-content: flex-end;
      background-color: white;
      box-sizing: border-box;
      padding: 10px 0;

      button {
        margin: 0;
        margin-left: 12px;
        width: 80px;
        height: 32px;
        line-height: 31px;
        background: #ffffff;
        border: 1px solid #404040;
        border-radius: 32px;
        font-size: 14px;
        color: #363636;
        padding: 0;

        &.primary {
          color: @primary-color;
          border-color: @primary-color;
        }

        &.red {
          color: @red-color;
          border-color: @red-color;
        }
        &.delete {
          color: @label-color;
          border-color: @label-color;
        }

        &::after {
          border: none;
        }
      }
    }
  }
}
</style>
